package 实现数据结构.实现队列;

import java.util.Arrays;

/**
 * @DESC page32 栈练习
 * 栈：FILO/LIFO
 * 使用场景：1.逆序输出 2.语法检查，成对出现 3. 数制转换
 * @Author tzq
 * @Date 2019-10-19 16:46
 **/
public class Stack {

    private int size;

    private int[] array;

    /*初始化栈大小*/
    public Stack(int init) {
        if (init <= 0) {
            init = 10;
        }
        array = new int[init];
    }

    // 入栈
    public void push(int item) {
        if (size == array.length) {
            array = Arrays.copyOf(array, size * 2);
        }

        array[size++] = item;
    }

    //获取栈顶元素，不出栈
    public int peek() {
        if (size == 0) {
            throw new IndexOutOfBoundsException("Stack is empty");
        }

        return array[size - 1];
    }

    //获取栈顶元素，出栈
    public int pop() {
        int top = peek();
        size--; //非真实清除数据，下次入栈操作即可覆盖旧数据
        return top;
    }

    //判断是否满了
    public boolean isFull() {
        return size == array.length;
    }

    //判断是否为空栈
    public boolean isEmpty() {
        return size == 0;
    }

    // 获取栈大小
    public int size() {
        return size;
    }


    // Test
    public static void main(String[] args) {
        Stack stack = new Stack(1);
        stack.push(1);
        stack.push(2);
        System.out.println(stack.size);


        stack.push(3);
        System.out.println("peek:" +stack.peek() + " size:" + stack.size);

        stack.pop();

        System.out.println("peek:" +stack.peek() + " size:" + stack.size);




    }
}
